import statistics
import logging

class PriceAnalyzer:
    def __init__(self):
        self.logger = logging.getLogger(__name__)
    
    def analyze(self, products):
        """分析价格数据并提供建议"""
        if not products:
            return {
                'min_price': 0,
                'max_price': 0,
                'avg_price': 0,
                'suggested_price': 0
            }
        
        prices = [p['price'] for p in products]
        
        # 基础统计
        min_price = min(prices)
        max_price = max(prices)
        avg_price = round(statistics.mean(prices), 2)
        
        # 销量加权平均（模拟）
        weighted_prices = []
        for product in products:
            try:
                sales_str = str(product.get('sales', '0')).replace('+', '')
                sales = int(sales_str) if sales_str.isdigit() else 100
                weighted_prices.extend([product['price']] * min(sales // 100, 10))  # 限制权重
            except:
                weighted_prices.append(product['price'])
        
        weighted_avg = round(statistics.mean(weighted_prices), 2) if weighted_prices else avg_price
        
        # 建议定价算法
        # 1. 不能低于最低价的95%（避免恶性竞争）
        # 2. 考虑销量加权平均
        # 3. 考虑市场接受度
        suggested_price = round(
            max(
                min_price * 0.95,
                weighted_avg * 0.98
            ), 2
        )
        
        # 确保建议价格在合理范围内
        suggested_price = max(min_price, min(suggested_price, max_price * 0.9))
        
        return {
            'min_price': min_price,
            'max_price': max_price,
            'avg_price': avg_price,
            'suggested_price': suggested_price,
            'total_products': len(products),
            'price_distribution': {
                'low': len([p for p in prices if p < avg_price * 0.8]),
                'medium': len([p for p in prices if avg_price * 0.8 <= p <= avg_price * 1.2]),
                'high': len([p for p in prices if p > avg_price * 1.2])
            }
        }
    
    def get_pricing_strategy(self, analysis_result):
        """提供定价策略建议"""
        min_price = analysis_result['min_price']
        max_price = analysis_result['max_price']
        suggested_price = analysis_result['suggested_price']
        
        price_range = max_price - min_price
        
        if price_range < min_price * 0.1:
            strategy = "价格竞争激烈，建议采用差异化策略"
        elif suggested_price < min_price * 1.05:
            strategy = "建议定价接近最低价，快速占领市场"
        elif suggested_price > max_price * 0.85:
            strategy = "建议定价接近最高价，突出品质优势"
        else:
            strategy = "建议定价处于中等水平，平衡价格与销量"
        
        return {
            'strategy': strategy,
            'confidence': 'high' if analysis_result['total_products'] > 10 else 'medium',
            'risk_level': 'low' if price_range < min_price * 0.2 else 'medium'
        }
